package com.raja.servingStation.controller;

import com.alibaba.fastjson.JSONObject;
import com.raja.servingStation.common.exception.BusinessRuntimeException;
import com.raja.servingStation.common.util.*;
import com.raja.servingStation.entity.ServingStation;
import com.raja.servingStation.service.ServingStationService;
import com.raja.servingStation.service.TbOrderService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录控制器
 * Created by liuyanjun
 * on 2017/4/5.
 */
@RestController
public class LoginController {
    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private ResponseUtil responseUtil;
    @Autowired
    private ServingStationService servingStationService;
    @Autowired
    private MacAddressUtil macAddressUtil;
    @Autowired
    private CheckCodeUtil checkCodeUtil;
    @Autowired
    private TbOrderService tbOrderService;




    /**
     * 登录页
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ResponseEntity loginPost(HttpServletRequest request, HttpServletResponse response){
        try {
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*"); //解决跨域访问报错
            JSONObject bodyJson = RequestUtil.parseBody(request);
            String loginName = bodyJson.getString("loginName");
            String password = bodyJson.getString("password");
            String code = bodyJson.getString("code");
            String uniqueClient = bodyJson.getString("uniqueClient");
            checkLoginParam(loginName,password,code,uniqueClient);
            String checkCode = checkCodeUtil.getCacheKey(uniqueClient);
            if(checkCode == null)
                return responseUtil.exception(ReturnCodes.CODES_EXPIRED);
            if(code.equalsIgnoreCase(checkCode)){
                ServingStation servingStation =  servingStationService.getUserByLoginName(loginName);
                Double score = tbOrderService.queryOrderScore(servingStation.getId());
                servingStation.setScore(score==null?0:score);
                if(servingStation == null)
                    return  responseUtil.exception(ReturnCodes.USER_NO_EXITS);
                else {
                    if(!password.equals(servingStation.getPassword())){
                        return  responseUtil.exception(ReturnCodes.PASSWORD_ERROR);
                    }else {
                        servingStation.setPassword(null);
                        return responseUtil.success(servingStation, servingStation.getId().intValue());
                    }
                }
            }else
              return   responseUtil.exception(ReturnCodes.CODES_ERROR);
        }catch (BusinessRuntimeException ee){
            log.error(ee.getMessage());
            return responseUtil.exception(ee.getMessage());
        }
        catch (Exception e){
            log.error(e.getMessage(),e);
            return responseUtil.exception(ReturnCodes.REQUEST_EXCEPTION);
        }
    }

    private void checkLoginParam(String loginName, String password, String verificatioCode,String uniqueClient) throws BusinessRuntimeException {
        AssertUtils.assertNotNull(loginName);
        AssertUtils.assertNotNull(password);
        AssertUtils.assertNotNull(verificatioCode);
        AssertUtils.assertNotNull(uniqueClient);
    }

    /**
     *  获取验证码
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCode",method = RequestMethod.GET)
    public ResponseEntity getCode(HttpServletRequest request,HttpServletResponse response){
        try {
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*"); //解决跨域访问报错
            JSONObject parseBody = RequestUtil.parseBody(request);
            String uniqueClient = parseBody.getString("uniqueClient");
            if(uniqueClient == null)
                return responseUtil.exception(ReturnCodes.ERR_param_ERROR);
            String ip = macAddressUtil.getIpAddr(request);
            //记录IP
            checkCodeUtil.checkIpVistTimes(ip);
            // 设置响应的类型格式为图片格式
            response.setContentType("image/jpeg");
            // 禁止图像缓存。
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            //生成随机字串
            String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
            //生成图片
            int w = 200, h = 80;
            VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
            checkCodeUtil.setCacheKey(uniqueClient,verifyCode);
            return responseUtil.noTokenSuccess(ReturnCodes.GET_CODE_SUCCESS);
        }catch (BusinessRuntimeException b){
            log.error(b.getMessage(),b);
            return responseUtil.exception(b.getMessage());
        } catch (Exception e){
            log.error(e.getMessage(),e);
            return responseUtil.exception(ReturnCodes.REQUEST_EXCEPTION);
        }
    }

    /**
     * 忘记密码修改密码
     * @param request
     * @return
     */
    @RequestMapping(value = "/updatePassword",method = RequestMethod.POST)
    public ResponseEntity updatePassword(HttpServletRequest request,HttpServletResponse response){
        try {
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*"); //解决跨域访问报错
            JSONObject parseBody = RequestUtil.parseBody(request);
            String loginName = parseBody.getString("loginName");
            String code = parseBody.getString("code");
            String newPassword = parseBody.getString("newPassword");
            String secondNewPassword = parseBody.getString("secondNewPassword");
            if(loginName == null )
                return responseUtil.exception(ReturnCodes.ERR_param_ERROR);
            if(code == null || code.trim().length()!=6)
                return responseUtil.exception(ReturnCodes.CODES_ERROR);
            if(newPassword == null || newPassword.trim().length() !=32)
                return responseUtil.exception(ReturnCodes.ERR_param_ERROR);
            if(!newPassword.equals(secondNewPassword))
                return responseUtil.exception(ReturnCodes.TWO_PASSWORD_NO_EQUAL);
            String checkCode = checkCodeUtil.checkCode(loginName);
            if(checkCode == null)
                return responseUtil.exception(ReturnCodes.CODES_EXPIRED);
            if(checkCode.equals(code)){
//                UserInfo userInfo = new UserInfo(userPhone,newPassword);
//                userService.updateForgetPassword(userInfo);
                return responseUtil.noTokenSuccess(ReturnCodes.OPERATION_SUCCESS);
            }else {
                return responseUtil.exception(ReturnCodes.CODES_ERROR);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return responseUtil.exception(ReturnCodes.REQUEST_EXCEPTION);
        }
    }



    /**
     * 错误页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/error/403")
    public String error(HttpServletRequest request, HttpServletResponse response){
        return "/error/403";
    }

    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("aa",12);
        System.out.println(jsonObject.getInteger("bb"));
    }


    @RequestMapping(value = "getMac")
    public void getMac(HttpServletRequest request,HttpServletResponse response){
        try {
            MacAddressUtil macAddressUtil = new MacAddressUtil();
            String ip = macAddressUtil.getIpAddr(request);
            String mac = macAddressUtil.getMacInWindows(ip);
            response.getWriter().print(ip);
            response.getWriter().print(mac);
        }catch (Exception e){
            e.getCause();
        }
    }
}
